package org.jeecg.modules.staff.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.bicycle.order.mapper.BikeVehicleOrderMapper;
import org.jeecg.modules.bicycle.order.vo.SwitchLockRes;
import org.jeecg.modules.bicycle.vehicle.entity.BikeVehicle;
import org.jeecg.modules.bicycle.vehicle.mapper.BikeVehicleMapper;
import org.jeecg.modules.constant.BikeConstant;


import org.jeecg.modules.dto.device.SetVoiceReq;
import org.jeecg.modules.home.monitoring.entity.MonitoringMap;
import org.jeecg.modules.home.monitoring.entity.MonitoringStation;
import org.jeecg.modules.home.monitoring.mapper.MonitoringMapper;
import org.jeecg.modules.home.monitoring.service.MonitoringService;
import org.jeecg.modules.home.monitoring.vo.MonitoringMapReq;
import org.jeecg.modules.param.area.entity.BikeSysArea;
import org.jeecg.modules.param.area.entity.BikeSysUserArea;
import org.jeecg.modules.param.area.mapper.BikeSysAreaMapper;
import org.jeecg.modules.param.area.mapper.BikeSysUserAreaMapper;
import org.jeecg.modules.param.fault.entity.BikeFaultSubmit;
import org.jeecg.modules.param.fault.mapper.BikeFaultSubmitMapper;
import org.jeecg.modules.param.maintain.mapper.BikePileLockMapper;
import org.jeecg.modules.param.pile.entity.BikePile;
import org.jeecg.modules.param.pile.mapper.BikePileMapper;
import org.jeecg.modules.param.staffUser.entity.LoginRes;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.mapper.BikeStationMapper;
import org.jeecg.modules.param.staffUser.mapper.StaffMapper;
import org.jeecg.modules.param.sysparam.entity.BikeSysParam;
import org.jeecg.modules.service.DeviceService;
import org.jeecg.modules.staff.order.dto.StationReq;
import org.jeecg.modules.staff.order.dto.TaskDto;
import org.jeecg.modules.staff.order.entity.ClockReq;
import org.jeecg.modules.staff.order.entity.ScanCodeReq;
import org.jeecg.modules.staff.order.mapper.OrderMapper;
import org.jeecg.modules.staff.order.service.OrderService;
import org.jeecg.modules.utils.BikeResult;
import org.jeecg.modules.utils.RandomCodeUtils;
import org.jeecg.modules.utils.YueYueNiaoUtils;
import org.jeecg.modules.work.dispatch.entity.BikeWorkDispatch;
import org.jeecg.modules.work.dispatch.mapper.BikeWorkDispatchMapper;
import org.jeecg.modules.work.file.entity.BikeWorkSubmitFile;
import org.jeecg.modules.work.file.mapper.BikeWorkSubmitFileMapper;
import org.jeecg.modules.work.repair.entity.BikeWorkRepair;
import org.jeecg.modules.work.repair.mapper.BikeWorkRepairMapper;
import org.jeecg.modules.work.sweep.dto.WorkReq;
import org.jeecg.modules.work.sweep.entity.BikeWorkSweep;
import org.jeecg.modules.work.sweep.mapper.BikeWorkSweepMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private BikeWorkRepairMapper bikeWorkRepairMapper;
    @Autowired
    private BikeWorkSweepMapper bikeWorkSweepMapper;
    @Autowired
    private BikeWorkDispatchMapper bikeWorkDispatchMapper;
    @Autowired
    private BikeWorkSubmitFileMapper bikeWorkSubmitFileMapper;
    @Autowired
    private BikePileMapper bikePileMapper;
    @Autowired
    private BikeStationMapper bikeStationMapper;
    @Autowired
    private BikePileLockMapper bikePileLockMapper;
    @Autowired
    private StaffMapper staffMapper;
    @Autowired
    private BikeVehicleMapper bikeVehicleMapper;
    @Autowired
    private BikeVehicleOrderMapper bikeVehicleOrderMapper;
    @Autowired
    private BikeFaultSubmitMapper bikeFaultSubmitMapper;
    @Autowired
    private BikeSysAreaMapper bikeSysAreaMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Resource
    private BikeSysUserAreaMapper bikeSysUserAreaMapper;

    @Resource
    private MonitoringMapper monitoringMapper;

    @Autowired
    private MonitoringService monitoringService;
    @Autowired
    private DeviceService deviceService;
    @Override
    public BikeResult getOrderList(Integer pageNum,Integer pageSize,HttpServletRequest request) {

        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginRes::getUsername,username);
        LoginRes  loginRes = staffMapper.selectOne(queryWrapper);
        Page<TaskDto> page = new Page<>(pageNum,pageSize);
        Map params = new HashMap();
        params.put("userId", loginRes.getId());
        IPage<TaskDto> orderList = orderMapper.getOrderList(page,params);

        return BikeResult.ok("1","成功",orderList);
    }

    /**
     * 根据类型查询工单
     * @param workReq
     * @param request
     * @return
     */
    @Override
    public BikeResult getWorkOrderList(WorkReq workReq, HttpServletRequest request) {
        //根据token 获取用户信息
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginRes::getUsername,username);
        LoginRes  loginRes = staffMapper.selectOne(queryWrapper);
            //保洁
            if (workReq.getOrderType().equals("1")){
                //分页
                Page<BikeWorkSweep> page = new Page<>(workReq.getPageNum(),workReq.getPageSize(),true);
                LambdaQueryWrapper<BikeWorkSweep> lambdaQueryWrapper  =new LambdaQueryWrapper<>();

                lambdaQueryWrapper.eq(BikeWorkSweep::getUserId,loginRes.getId());
                lambdaQueryWrapper.eq(BikeWorkSweep::getIsDispatch,"1");

                //排序规则 未解决 ---> 加急 --->时间  正序
                lambdaQueryWrapper.orderByAsc(BikeWorkSweep::getIsSolve,BikeWorkSweep::getUrgentType).orderByDesc(BikeWorkSweep::getDispatchTime);

                IPage<BikeWorkSweep> pageList= bikeWorkSweepMapper.selectPage(page,lambdaQueryWrapper);
                //添加是否完成
                for (BikeWorkSweep ws : pageList.getRecords()){
                    if (ws.getIsSolve().equals(BikeConstant.y_n_yes)||ws.getActualTime()!=null){
                        ws.setIsFinish(BikeConstant.y_n_yes);
                    }else {
                        ws.setIsFinish(BikeConstant.y_n_no);
                    }
                }

                return BikeResult.ok("1","成功",pageList);
            //维修
            }else if (workReq.getOrderType().equals("3")){
                Page<BikeWorkRepair> page = new Page<>(workReq.getPageNum(),workReq.getPageSize(),true);
                LambdaQueryWrapper<BikeWorkRepair> lambdaQueryWrapper  =new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(BikeWorkRepair::getUserId,loginRes.getId());
                lambdaQueryWrapper.eq(BikeWorkRepair::getIsDispatch,"1");
                lambdaQueryWrapper.orderByAsc(BikeWorkRepair::getIsSolve,BikeWorkRepair::getUrgentType).orderByDesc(BikeWorkRepair::getDispatchTime);
                IPage<BikeWorkRepair> pageList= bikeWorkRepairMapper.selectPage(page,lambdaQueryWrapper);
                //添加是否完成
                for (BikeWorkRepair ws : pageList.getRecords()){
                    if (ws.getIsSolve().equals(BikeConstant.y_n_yes)||ws.getActualTime()!=null){
                        ws.setIsFinish(BikeConstant.y_n_yes);
                    }else {
                        ws.setIsFinish(BikeConstant.y_n_no);
                    }
                }
                return BikeResult.ok("1","成功",pageList);
            }else if (workReq.getOrderType().equals("2")){
                //调度
                Page<BikeWorkDispatch> page = new Page<>(workReq.getPageNum(),workReq.getPageSize(),true);
                LambdaQueryWrapper<BikeWorkDispatch> lambdaQueryWrapper  =new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(BikeWorkDispatch::getUserId,loginRes.getId());
                lambdaQueryWrapper.eq(BikeWorkDispatch::getIsDispatch,"1");
                lambdaQueryWrapper.orderByAsc(BikeWorkDispatch::getIsSolve,BikeWorkDispatch::getUrgentType,BikeWorkDispatch::getDispatchTime).orderByDesc(BikeWorkDispatch::getDispatchTime);
                IPage<BikeWorkDispatch> pageList= bikeWorkDispatchMapper.selectPage(page,lambdaQueryWrapper);
                //添加是否完成
                for (BikeWorkDispatch ws : pageList.getRecords()){
                    if (ws.getIsSolve().equals(BikeConstant.y_n_yes)||ws.getActualTime()!=null){
                        ws.setIsFinish(BikeConstant.y_n_yes);
                    }else {
                        ws.setIsFinish(BikeConstant.y_n_no);
                    }
                }
                return BikeResult.ok("1","成功",pageList);
            }else {
                return BikeResult.ok("1","成功",null);
            }
    }






    @Override
    public BikeResult repairPunchClock(ClockReq clockReq, HttpServletRequest request) {
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        //管理员信息
        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginRes::getUsername,username);
        LoginRes  loginRes = staffMapper.selectOne(queryWrapper);


        if (clockReq.getUserType().equals("2")){
            //调度
            BikeWorkDispatch bikeWorkDispatch = new BikeWorkDispatch();
            bikeWorkDispatch.setId(clockReq.getId());
            bikeWorkDispatch.setIsSolve(clockReq.getIsSolve());
            bikeWorkDispatch.setContent(clockReq.getContent());
            bikeWorkDispatch.setActualTime(new Date());
            bikeWorkDispatch.setActualAddress(clockReq.getAddress());
            //判断不为空
            if (clockReq.getFilesItem()!=null&&!clockReq.getFilesItem().isEmpty()){
                if (clockReq.getFilesItem().size()>0){
                    List<ClockReq.FilesList> filesLists = clockReq.getFilesItem();
                    for (ClockReq.FilesList cf:filesLists) {
                        bikeWorkSubmitFileMapper.insert(new BikeWorkSubmitFile().setWorkId(clockReq.getId()).setWorkType("2").setFileUrl(cf.getFileUrl()));
                    }
                }
            }
           int param= bikeWorkDispatchMapper.updateById(bikeWorkDispatch);
            if (clockReq.getIsSolve().equals("1")){
                BikeWorkDispatch bikeWorkDispatch1 = bikeWorkDispatchMapper.selectById(clockReq.getId());
                if (bikeWorkDispatch1.getWorkSource().equals("3")){
                    updateSubmit(bikeWorkDispatch1.getSourceId());
                }
            }

            if (param==1){
                return BikeResult.ok("1","打卡成功",param);
            }
        }else if (clockReq.getUserType().equals("3")){
            //维修
            BikeWorkRepair bikeWorkRepair = new BikeWorkRepair();
            bikeWorkRepair.setId(clockReq.getId());
            bikeWorkRepair.setIsSolve(clockReq.getIsSolve());
            bikeWorkRepair.setContent(clockReq.getContent());
            bikeWorkRepair.setActualAddress(clockReq.getAddress());
            bikeWorkRepair.setActualTime(new Date());

            if (clockReq.getFilesItem()!=null &&!clockReq.getFilesItem().isEmpty()){
                if (clockReq.getFilesItem().size()>0){
                    List<ClockReq.FilesList> filesLists = clockReq.getFilesItem();
                    for (ClockReq.FilesList cf:filesLists) {
                        bikeWorkSubmitFileMapper.insert(new BikeWorkSubmitFile().setWorkId(clockReq.getId()).setWorkType("3").setFileUrl(cf.getFileUrl()));
                    }
                }
            }
           int param= bikeWorkRepairMapper.updateById(bikeWorkRepair);
            if (clockReq.getIsSolve().equals("1")){

                BikeWorkRepair bikeWorkRepair1 = bikeWorkRepairMapper.selectById(clockReq.getId());
                //查询网点信息
                QueryWrapper<BikeStation> bikeStationQueryWrapper = new QueryWrapper<>();
                bikeStationQueryWrapper.eq("code",bikeWorkRepair1.getStationCode());
                BikeStation bikeStation = bikeStationMapper.selectOne(bikeStationQueryWrapper);
                //通过网点信息锁定车桩信息
                QueryWrapper<BikePile> bikePileQueryWrapper = new QueryWrapper<>();
                bikePileQueryWrapper.eq("code",bikeWorkRepair.getDeviceCode());
                bikePileQueryWrapper.eq("station_id",bikeStation);
                BikePile bikePile1 = bikePileMapper.selectOne(bikePileQueryWrapper);
                if (bikePile1!=null){
                    BikePile bikePile = new BikePile();
                    bikePile.setPileStatus("1");
                    bikePileMapper.update(bikePile,new QueryWrapper<BikePile>().eq("code",bikeWorkRepair1.getDeviceCode()));
                }
                BikeVehicle bikeVehicle = bikeVehicleMapper.selectOne(new QueryWrapper<BikeVehicle>().eq("code", bikeWorkRepair1.getDeviceCode()));
                if (bikeVehicle!=null){
                    BikeVehicle bikeVehicle1 = new BikeVehicle();
                    bikeVehicle1.setStatus("3");
                    bikeVehicleMapper.update(bikeVehicle1,new QueryWrapper<BikeVehicle>().eq("code",bikeWorkRepair1.getDeviceCode()));
                }

                BikeWorkRepair bikeWorkRepair2 = bikeWorkRepairMapper.selectById(clockReq.getId());
                if (bikeWorkRepair2!=null){
                    if (bikeWorkRepair2.getWorkSource().equals("3")){
                        updateSubmit(bikeWorkRepair2.getSourceId());
                    }
                }else {
                    return BikeResult.error("0",clockReq.getId()+":打卡失败",null);
                }

            }

            if (param==1){
                return BikeResult.ok("1","打卡成功",param);
            }
        }
        return BikeResult.error("0","打卡失败",null);
    }




    /**
     * 保洁扫码打卡
     */
    @Override
    public BikeResult cleaningPunchClock(ScanCodeReq scanCodeReq, HttpServletRequest request) {
        //判断车桩扫码编号长度
        if (scanCodeReq.getDeviceCode().length()!=11){
            return BikeResult.error("0","无效的车桩编号",null);
        }
        //判断二维码是否正确
        String stationCode = scanCodeReq.getDeviceCode().substring(0, 5);
        String pileCode = scanCodeReq.getDeviceCode().substring(5, 7);
        String checkCode = scanCodeReq.getDeviceCode().substring(7,11);
        BikeStation stationData = bikeStationMapper.selectOne(new QueryWrapper<BikeStation>().eq("code", stationCode));
        if (stationData==null){
            return BikeResult.error("0","无效的车桩编号",null);
        }
        //查询车桩 根据车桩号后四位
        BikePile bikePileData = bikePileMapper.selectOne(new QueryWrapper<BikePile>()
                .eq("station_id",stationData.getId())
                .eq("code",pileCode)
                .eq("check_code",checkCode)
        );
        if (bikePileData==null){
            return BikeResult.error("0","无效的车桩编号",null);
        }
        //token认证 loginRes扫码人信息
        //String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        //String username = JwtUtil.getUsername(token);
        //LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        //queryWrapper.eq(LoginRes::getUsername,username);
        //LoginRes  loginRes = staffMapper.selectOne(queryWrapper);
        //查询此工单内容
        QueryWrapper<BikeWorkSweep> qw = new QueryWrapper<>();
        qw.eq("code",scanCodeReq.getCode());
        BikeWorkSweep workSweep = bikeWorkSweepMapper.selectOne(qw);
        if (workSweep==null){
            return BikeResult.error("0","未找到匹配工单",null);
        }
        if (!workSweep.getStationCode().equals(stationCode)){
            return BikeResult.error("0","车桩与工单不匹配",null);
        }else {
            if (!pileCode.equals(workSweep.getDeviceCode())){
                return BikeResult.error("0","车桩与工单不匹配",null);
            }
        }
        //新保洁工单对象
        //处理描述
        workSweep.setContent(scanCodeReq.getContent());
        //是否解决
        workSweep.setIsSolve(scanCodeReq.getIsSolve());
        //打卡地址
        workSweep.setActualAddress(scanCodeReq.getAddress());
        //打卡时间
        workSweep.setActualTime(new Date());
        int param=0;
        if (scanCodeReq.getIsSolve().equals("1")) {
            if (workSweep.getWorkSource().equals("3")) {
                updateSubmit(workSweep.getSourceId());
            }
        }

        if (scanCodeReq.getScanFilesLists()!=null&&!scanCodeReq.getScanFilesLists().isEmpty()){
            for (ScanCodeReq.ScanFilesList scanFilesList : scanCodeReq.getScanFilesLists()) {
                bikeWorkSubmitFileMapper.insert(new BikeWorkSubmitFile().setWorkId(workSweep.getId()).setWorkType("2").setFileUrl(scanFilesList.getFileUrl()));
            }
        }else {
            if (workSweep.getIsPicture().equals(BikeConstant.y_n_yes)){
                return BikeResult.error("0","缺少照片，打卡失败！",null);
            }
        }

        param = bikeWorkSweepMapper.updateById(workSweep);
        if (param==1){
            return BikeResult.ok("1","打卡成功",param);
        }else {

        }
        return BikeResult.error("0","打卡失败",null);
    }
    /**
     * 保洁签到扫码打卡
     */
    @Override
    public BikeResult cleaningSignInClock(ScanCodeReq scanCodeReq, HttpServletRequest request) {
        //判断车桩扫码编号长度
        if (scanCodeReq.getDeviceCode().length() != 11) {
            return BikeResult.error("0", "无效的车桩编号", null);
        }
        String stationCode = scanCodeReq.getDeviceCode().substring(0, 5);
        String pileCode = scanCodeReq.getDeviceCode().substring(5, 7);
        String checkCode = scanCodeReq.getDeviceCode().substring(7, 11);
        BikeStation stationData = bikeStationMapper.selectOne(new QueryWrapper<BikeStation>().eq("code", stationCode));
        if (stationData == null) {
            return BikeResult.error("0", "无效的车桩编号", null);
        }
        //查询车桩 根据车桩号后四位随机码
        BikePile bikePileData = bikePileMapper.selectOne(new QueryWrapper<BikePile>()
                .eq("station_id", stationData.getId())
                .eq("code", pileCode)
        );
        if (bikePileData == null) {
            return BikeResult.error("0", "无效的车桩编号", null);
        }

        //token认证 loginRes扫码人信息
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginRes::getUsername, username);
        LoginRes loginRes = staffMapper.selectOne(queryWrapper);

        //查询获取指定车桩，车站 并未解决的保洁工单
        QueryWrapper<BikeWorkSweep> qw = new QueryWrapper<>();
        qw.eq("device_code", pileCode);
        qw.eq("station_code", stationCode);
        qw.eq("is_solve", BikeConstant.y_n_no);
        qw.eq("is_dispatch",BikeConstant.y_n_yes);
        qw.eq("user_id", loginRes.getId());
        qw.isNull("actual_time");
        BikeWorkSweep workSweep = bikeWorkSweepMapper.selectOne(qw);
        if (workSweep != null) {
            return cleaningPunchClock(scanCodeReq, request);
        }

        //新保洁工单对象
        BikeWorkSweep bikeWorkSweep = new BikeWorkSweep();
        bikeWorkSweep.setContent(scanCodeReq.getContent());
        bikeWorkSweep.setIsSolve(scanCodeReq.getIsSolve());
        bikeWorkSweep.setAddress(scanCodeReq.getAddress());
        bikeWorkSweep.setActualAddress(scanCodeReq.getAddress());
        List<ScanCodeReq.ScanFilesList> scanFilesLists = scanCodeReq.getScanFilesLists();


        int param = 0;

        //BikeVehicle vehicle = bikeVehicleMapper.selectOne(new QueryWrapper<BikeVehicle>().eq("code", scanCodeReq.getDeviceCode()));
        String uuid = YueYueNiaoUtils.getUUid();
        bikeWorkSweep.setId(uuid);
        bikeWorkSweep.setCode(RandomCodeUtils.getRandomCode("BJ"));
        bikeWorkSweep.setStationCode(stationData.getCode());
        bikeWorkSweep.setStationName(stationData.getName());
        bikeWorkSweep.setAddress(stationData.getAddress());
        bikeWorkSweep.setDeviceCode(pileCode);
        bikeWorkSweep.setRepairItem(BikeConstant.y_n_yes);
        bikeWorkSweep.setIsPicture("0");
        bikeWorkSweep.setUserId(loginRes.getId());
        bikeWorkSweep.setUserName(loginRes.getUsername());
        bikeWorkSweep.setFinishTime(new Date());
        bikeWorkSweep.setUrgentType("1");
        bikeWorkSweep.setIsDispatch("1");
        bikeWorkSweep.setDispatchTime(new Date());
        bikeWorkSweep.setActualTime(new Date());
        bikeWorkSweep.setWorkSource("1");

        if (scanFilesLists!=null&&!scanFilesLists.isEmpty()){
            for (ScanCodeReq.ScanFilesList scanFilesList : scanFilesLists) {
                bikeWorkSubmitFileMapper.insert(new BikeWorkSubmitFile().setWorkId(uuid).setWorkType("2").setFileUrl(scanFilesList.getFileUrl()));
            }
        }
        param = bikeWorkSweepMapper.insert(bikeWorkSweep);

        if (param == 1) {
            return BikeResult.ok("1", "打卡成功", param);
        }
        return BikeResult.error("0", "打卡失败", null);

    }

    @Override
    public BikeResult getByStationCode(String code, HttpServletRequest request) {
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(accessToken);
        //查询所负责的区域
        QueryWrapper<BikeSysUserArea> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",username);
        BikeSysUserArea bikeSysUserArea = bikeSysUserAreaMapper.selectOne(wrapper);
        MonitoringStation monitoringStation = new MonitoringStation();
        monitoringStation.setAreaUserArrayIds(Arrays.asList(bikeSysUserArea.getAreaId().split(",")));
        if (StringUtils.isNotEmpty(code)){
            monitoringStation.setStationCode(code);
        }
        List<MonitoringStation> monitoringStationList = monitoringMapper.homeListMapView(monitoringStation);

        return BikeResult.ok("1","查询成功",addHeartList(monitoringStationList));
    }
    private List<MonitoringStation> addHeartList(List<MonitoringStation> homeList) {

        for (int i = 0; i < homeList.size(); i++) {
            MonitoringStation monitoringStation = homeList.get(i);
            //int vehicleCount = monitoringMapper.getVehicleCountByStationId(monitoringStation.getStationId());
            //跳包数据
            if (StringUtils.isEmpty(monitoringStation.getPileBikeCount())){
                monitoringStation.setPileBikeCount("0");
            }
            int vehicleCount =Integer.parseInt(monitoringStation.getPileBikeCount());
            //获取车数/桩数
            monitoringStation.setPileBikeCount(vehicleCount + "/" + monitoringStation.getPileCount());
            if (monitoringStation.getHeartTime() != null) {
                DecimalFormat df = new DecimalFormat("0.0");
                //温度
                Double e = Double.valueOf(df.format(Double.valueOf(monitoringStation.getTemperature().toString().replace("E", ""))));
                monitoringStation.setTemperature(e);
                //电压
                monitoringStation.setVoltage(Double.valueOf(df.format(monitoringStation.getVoltage())));
                //湿度
                monitoringStation.setHumidity(Double.valueOf(df.format(monitoringStation.getHumidity())));

                //网点是否有车
                if (vehicleCount == 0) {
                    monitoringStation.setIsStationVehicle(BikeConstant.y_n_no);
                    monitoringStation.setAbnormal("2");
                } else {
                    monitoringStation.setIsStationVehicle(BikeConstant.y_n_yes);
                    monitoringStation.setAbnormal("1");
                }
                //是否故障
                if (monitoringStation.getErrCount() != 0) {
                    monitoringStation.setIsStationErr(BikeConstant.y_n_yes);
                    monitoringStation.setAbnormal("5");
                }

                //判断常闭
                if (monitoringStation.getIsLock().equals(BikeConstant.y_n_yes)) {
                    monitoringStation.setAbnormal("3");
                }


                //网点是否断线
                long updateTime = new Date().getTime() - monitoringStation.getHeartTime().getTime();
                if (BikeConstant.is_offline_time < updateTime) {
                    monitoringStation.setIsOffline(BikeConstant.y_n_yes);
                    monitoringStation.setAbnormal("4");
                } else {
                    monitoringStation.setIsOffline(BikeConstant.y_n_no);
                }


            } else {
                //网点是否断线
                monitoringStation.setIsOffline(BikeConstant.y_n_yes);
                monitoringStation.setAbnormal("4");
            }
        }

        return homeList;
    }


    @Override
    public BikeResult switchLock(Integer pageNum, Integer pageSize,HttpServletRequest request) {

        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);

        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginRes::getUsername,username);
        LoginRes  loginRes = staffMapper.selectOne(queryWrapper);

        Page<SwitchLockRes> page = new Page<>(pageNum,pageSize,true);
        IPage<SwitchLockRes> pageList= bikePileLockMapper.getPilePageList(page,loginRes.getId());

        return BikeResult.ok("1","获取开关锁详情成功",pageList);
    }

    @Override
    public BikeResult getByStationList(String areId, HttpServletRequest request) {
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(accessToken);

        //查询所负责的区域
        QueryWrapper<BikeSysUserArea> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",username);
        BikeSysUserArea bikeSysUserArea = bikeSysUserAreaMapper.selectOne(wrapper);
        if (bikeSysUserArea!=null){
            String ids = bikeSysUserArea.getAreaId();
            String[]  strings= ids.split(",");
            List<String> list = Arrays.asList(strings);
            QueryWrapper<BikeStation> qw = new QueryWrapper<>();
            qw.eq("status","1");
            if (StringUtils.isNotEmpty(areId)){
                qw.eq("area_id",areId);
            }
            qw.in("id",list);
            List<BikeStation> list1 = bikeStationMapper.selectList(qw);
            return BikeResult.ok("1","获取站点成功 ",list1);
        }
        return BikeResult.error("0","没有可操作的站点权限",null);
    }

    @Override
    public BikeResult getPileList(String stationId) {

        JSONObject job= new JSONObject();

        List<BikePile> bikePileList = bikePileMapper.selectList(new QueryWrapper<BikePile>().eq("station_id", stationId));
        int ycCount = 0;
        int inCount = 0 ;
        int wcCount = 0;
        if (!bikePileList.isEmpty()){
            for (BikePile bikePile : bikePileList){
                if (bikePile.getPileStatus().equals("0")){
                    ycCount++;
                }
                BikeVehicle vehicle = bikeVehicleMapper.selectOne(new QueryWrapper<BikeVehicle>().eq("pile_id", bikePile.getId()));
                if (vehicle!=null){
                    inCount++;
                }
            }
            wcCount=bikePileList.size()-inCount;
        }
        //车桩信息
        List<JSONObject> list= new ArrayList<>();
        List<BikePile> station = bikePileMapper.selectList(new QueryWrapper<BikePile>().eq("station_id", stationId));
        for (BikePile bikePile: station) {
            JSONObject jsonObject = new JSONObject();


            jsonObject.put("pileStatus",bikePile.getPileStatus());

            if (bikePile.getLockStatus().equals("0")){
                BikeVehicle bikeVehicle = bikeVehicleMapper.selectOne(new QueryWrapper<BikeVehicle>().eq("pile_id", bikePile.getId()));
                if (bikeVehicle==null){
                    jsonObject.put("lockStatus","1");
                }else {
                    jsonObject.put("lockStatus",bikeVehicle.getCode());
                }

            }else {
                jsonObject.put("lockStatus",bikePile.getLockStatus());
            }

            jsonObject.put("pileCode",bikePile.getCode());

            list.add(jsonObject);
        }
        job.put("abnormal",ycCount);
        job.put("warning","10");
        job.put("noCar",wcCount);
        job.put("inCar",inCount);
        job.put("data",list);

        return BikeResult.ok("1","获取车桩信息成功",job);
    }


    @Override
    public BikeResult getByStationId(String id) {
        JSONObject jsonObject = new JSONObject();

        List<JSONObject> list = new ArrayList<>();
        BikeStation bikeStation = bikeStationMapper.selectById(id);
        BikeSysArea bikeSysArea = bikeSysAreaMapper.selectById(bikeStation.getAreaId());
        List<BikePile> s = bikePileMapper.selectList(new QueryWrapper<BikePile>().eq("station_id", id));

        for (BikePile bikePile:s) {
            JSONObject job = new JSONObject();
            job.put("bileId",bikePile.getId());
            job.put("bileName",bikePile.getCode());
            list.add(job);

        }
        jsonObject.put("stationId",bikeStation.getId());
        jsonObject.put("stationName",bikeStation.getName());
        jsonObject.put("stationCode",bikeStation.getCode());
        jsonObject.put("areaName",bikeSysArea.getName());
        jsonObject.put("areaId",bikeSysArea.getId());
        jsonObject.put("data",list);
        return BikeResult.ok("1","成功",jsonObject);
    }

    @Override
    public BikeResult getPileById(String id,String stationId) {
        JSONObject jsonObject = new JSONObject();
        if (id.equals("-1")){
            jsonObject.put("id", null);
            jsonObject.put("pickVoice", null);
            jsonObject.put("returnVoice", null);
            jsonObject.put("errorVoice", null);
            jsonObject.put("volumeSize", null);
        }else {
            BikePile bikePile = bikePileMapper.selectOne(new QueryWrapper<BikePile>().eq("id",id).eq("station_id",stationId));

            jsonObject.put("id",bikePile.getId());
            if (StringUtils.isNotEmpty(bikePile.getPickVoice())){

                jsonObject.put("pickVoice",bikePile.getPickVoice());
            }else {
                jsonObject.put("pickVoice",null);
            }

            if (StringUtils.isNotEmpty(bikePile.getReturnVoice())){
                jsonObject.put("returnVoice",bikePile.getReturnVoice());
            }else {
                jsonObject.put("returnVoice",null);
            }

            if (StringUtils.isNotEmpty(bikePile.getErrorVoice())){
                jsonObject.put("errorVoice",bikePile.getErrorVoice());
            }else {
                jsonObject.put("errorVoice",null);
            }
            jsonObject.put("volumeSize",bikePile.getVolumeSize());
        }

        return BikeResult.ok("1","查询成功",jsonObject);
    }

    @Override
    public BikeResult updateStation(StationReq stationReq) {
        SetVoiceReq setVoiceReq = new SetVoiceReq();
        BikeStation bikeStation = bikeStationMapper.selectById(stationReq.getStationId());
        if (bikeStation==null||StringUtils.isEmpty(bikeStation.getCode())){
            return BikeResult.ok("0", "未找到网点", null);
        }else {
            setVoiceReq.setStationCode(bikeStation.getCode());
        }

        if (StringUtils.isEmpty(stationReq.getPileId())){
            setVoiceReq.setPileCode("0");
        }else {
            BikePile bikePile = bikePileMapper.selectById(stationReq.getPileId());
            if (bikePile==null||StringUtils.isEmpty(bikePile.getCode())){
                return BikeResult.ok("0", "未找到车桩", null);
            }else {
                setVoiceReq.setPileCode(bikePile.getCode());
            }
        }
        setVoiceReq.setPickVoice(stationReq.getPickVoice());
        setVoiceReq.setReturnVoice(stationReq.getReturnVoice());
        setVoiceReq.setErrorVoice(stationReq.getErrorVoice());
        setVoiceReq.setVolumeSize(stationReq.getVolumeSize());
        Result<?> result = deviceService.updateVoice(setVoiceReq);
        if (result.getCode()==200){
            return BikeResult.ok("1", "修改成功", null);
        }else {
            return BikeResult.ok("0", "修改失败", null);
        }
    }




    public int updateSubmit(String sourceId){
        BikeFaultSubmit bikeFaultSubmit = new BikeFaultSubmit();
        bikeFaultSubmit.setId(sourceId);
        bikeFaultSubmit.setIsSolve("1");
        int i = bikeFaultSubmitMapper.updateById(bikeFaultSubmit);
      return i;
    }





}
